<script setup lang="ts">
import type { TableColumnProps } from 'ant-design-vue';

import { onMounted, ref } from 'vue';

import { DictEnum } from '@vben/constants';

import { message } from 'ant-design-vue';

import { customerTransferApi } from '#/api/hm/customer/transfer';
import { deptList } from '#/api/system/dept';
import { DictTag } from '#/components/dict';
import { getDictOptions } from '#/utils/dict';

import CustomerBatchTransferModal from './components/CustomerBatchTransferModal.vue';
import CustomerSingleTransferModal from './components/CustomerSingleTransferModal.vue';

// 响应式数据
const selectedStoreId = ref<number>();
const storeList = ref<any[]>([]);
const resignedStaffList = ref<any[]>([]);
const customerList = ref<any[]>([]);
const activeStaffList = ref<any[]>([]);
const batchTransferVisible = ref(false);
const singleTransferVisible = ref(false);
const selectedStaff = ref<any>();
const selectedCustomer = ref<any>();
const oldStaffName = ref<any>('');

// 客户表格列配置
const customerColumns: TableColumnProps[] = [
  { title: '客户姓名', dataIndex: 'customerName', key: 'customerName' },
  { title: '电话', dataIndex: 'phone', key: 'phone' },
  { title: '会员等级', dataIndex: 'memberLevel', key: 'memberLevel' },
  { title: '客户类型', dataIndex: 'customerType', key: 'customerType' },
  // {
  //   title: '最后维护时间',
  //   dataIndex: 'lastMaintainDate',
  //   key: 'lastMaintainDate',
  // },
  { title: '操作', key: 'action', width: 100 },
];

// 方法
const loadResignedStaffCustomers = async () => {
  try {
    const data = await customerTransferApi.getResignedStaffCustomers(
      selectedStoreId.value,
    );
    resignedStaffList.value = data.userLeaveList;
    // 处理列表,增加原负责员工信息
    resignedStaffList.value.forEach((staff) => {
      staff.customerCount = staff.customerList.length;
    });
    activeStaffList.value = data.userList;
  } catch {
    message.error('加载离职员工客户数据失败');
  }
};

const handleStoreChange = () => {
  loadResignedStaffCustomers();
  // loadActiveStaff();
};

const openBatchTransferModal = (staff: any) => {
  selectedStaff.value = staff;
  batchTransferVisible.value = true;
};

const openSingleTransferModal = (customer: any, staff: any) => {
  selectedCustomer.value = customer;
  selectedStaff.value = staff;
  singleTransferVisible.value = true;
};

const handleTransferSuccess = () => {
  message.success('客户迁移成功');
  loadResignedStaffCustomers();
};

const loadStoreList = async () => {
  const requestParams = { ancestors: '101', deptCategory: 'DP' };
  const deptTree = await deptList(requestParams);
  const deptOptions = [];
  const deptTransOptions = deptTree.map((item) => ({
    label: item.deptName,
    value: item.deptId,
  }));
  deptOptions.push(...deptTransOptions);
  storeList.value = deptOptions;
};

onMounted(() => {
  // 初始化店铺列表
  loadStoreList();
});
</script>

<template>
  <div class="customer-transfer-container">
    <a-card title="离职员工客户迁移" :bordered="false">
      <!-- 店铺筛选 -->
      <div class="filter-section mb-4">
        <a-space>
          <span>选择店铺：</span>
          <a-select
            v-model:value="selectedStoreId"
            placeholder="请选择店铺"
            style="width: 200px"
            @change="handleStoreChange"
          >
            <a-select-option
              v-for="store in storeList"
              :key="store.value"
              :value="store.value"
            >
              {{ store.label }}
            </a-select-option>
          </a-select>
        </a-space>
      </div>

      <!-- 离职员工列表 -->
      <div class="resigned-staff-section">
        <h3>离职员工及其客户</h3>
        <a-empty
          v-if="resignedStaffList.length === 0"
          description="暂无离职员工客户数据"
        />

        <div v-else class="staff-cards">
          <a-card
            v-for="staff in resignedStaffList"
            :key="staff.userId"
            :title="`${staff.nickName} (${staff.customerList.length}个客户)`"
            class="staff-card mb-4"
          >
            <template #extra>
              <a-button type="primary" @click="openBatchTransferModal(staff)">
                批量迁移
              </a-button>
            </template>

            <!-- 客户列表 -->
            <a-table
              :columns="customerColumns"
              :data-source="staff.customerList"
              :pagination="false"
              row-key="customerId"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'action'">
                  <a-button
                    type="link"
                    size="small"
                    @click="openSingleTransferModal(record, staff)"
                  >
                    单独迁移
                  </a-button>
                </template>
                <template v-if="column.key === 'memberLevel'">
                  <DictTag
                    v-if="record.memberLevel"
                    :dicts="getDictOptions(DictEnum.SYS_MEMBER_LEVEL)"
                    :value="record[column.key]"
                  />
                  <span v-else>-</span>
                </template>
                <template v-if="column.key === 'customerType'">
                  <DictTag
                    v-if="record.customerType"
                    :dicts="getDictOptions(DictEnum.SYS_CUSTOMER_TYPE)"
                    :value="record[column.key]"
                  />
                  <span v-else>-</span>
                </template>
              </template>
            </a-table>
          </a-card>
        </div>
      </div>
    </a-card>

    <!-- 批量迁移弹窗 -->
    <CustomerBatchTransferModal
      v-model:visible="batchTransferVisible"
      :staff-info="selectedStaff"
      :active-staff-list="activeStaffList"
      @success="handleTransferSuccess"
    />

    <!-- 单个迁移弹窗 -->
    <CustomerSingleTransferModal
      v-model:visible="singleTransferVisible"
      :customer-info="selectedCustomer"
      :from-staff="selectedStaff"
      :active-staff-list="activeStaffList"
      @success="handleTransferSuccess"
    />
  </div>
</template>
